﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using API;
using CoreGraphics;
using Foundation;
using Masonry;
using MyExtensions;
using UIKit;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace mb.iOS
{
    public class StartViewController : UIViewController, API.IUpdateNotify, IUIPopoverPresentationControllerDelegate
    {
        static ILog logger = mb.ServiceLocator.Instance.Get<ILog>();
        static IStartOption startOption = ServiceLocator.Instance.Get<IStartOption>();
        string updateGroup = "test";
        bool isLoading = true;

        UILabel LabVersion;
        UILabel LabTitle;
        UIProgressView PrgUpdate;
        UIView MagicView;
        UIImageView LogoView;

        public override async void ViewDidLoad()
        {
            base.ViewDidLoad();

            var bkView = new UIView() { BackgroundColor = UIColor.White };
            bkView.SetParent(View).MakeConstraints(m =>
            {
                // m.Top.EqualTo(this.TopLayoutGuideBottom());
                m.Top.EqualTo(View);
                m.Left.Right.Bottom.EqualTo(View);
            });

            LabVersion = new UILabel();
            LabTitle = new UILabel();
            PrgUpdate = new UIProgressView();
            LogoView = new UIImageView();

            LabVersion.SetParent(View).MakeConstraints(make =>
            {
                make.Bottom.EqualTo(this.BottomLayoutGuideTop());
                make.CenterX.EqualTo(View);
            });
            var bt = mb.AssemblyCreationDate.Value;
            LabVersion.Font = UIFont.FromName("Marion", 18);
            LabVersion.Text = Xamarin.Essentials.AppInfo.VersionString + " @ " + bt.ToShortDateString() + ' ' + bt.ToShortTimeString();

            LabTitle.SetParent(View).MakeConstraints(make =>
            {
                make.CenterX.EqualTo(View);
                make.Bottom.EqualTo(View).Offset(-100);
            });
            LabTitle.Text = "正在加载中";
            UIView.Animate(0.5f, 0,
                UIViewAnimationOptions.Autoreverse |
                UIViewAnimationOptions.CurveEaseInOut |
                UIViewAnimationOptions.Repeat,
                () =>
                {
                    LabTitle.Alpha = 0.0f;
                }, null);

            PrgUpdate.SetParent(View).MakeConstraints(make =>
            {
                make.Top.EqualTo(LabTitle.Bottom()).Offset(10);
                make.CenterX.EqualTo(View);
                make.Width.EqualTo(View).MultipliedBy(0.5f);
            });
            PrgUpdate.Hidden = true;
            PrgUpdate.TintColor = App.MainColor;

            LogoView.SetParent(View).MakeConstraints(m =>
            {
                m.Center.EqualTo(View);
                m.Width.EqualTo(NSObject.FromObject(300));
                m.Height.EqualTo(NSObject.FromObject(300));
            });
            LogoView.Image = UIImage.FromBundle("logo");

            //进默认服务器的全屏按钮
            var dbtn = new UIButton() { };
            dbtn.SetParent(View).MakeConstraints(m => m.Edges.EqualTo(View));
            dbtn.TouchUpInside += (s, e) =>
            {
                if( isLoading ) return;
                StartUpdate("default", App.AssetServerURI.Item1, App.AssetServerURI.Item2);
            };

            //打开选dev服务器的彩蛋按钮
            mb.Util.DoWhenTestFlag(() =>
            {
                var mbtn = new UIButton() { BackgroundColor = App.MainColor.ColorWithAlpha(0.5f) };
                mbtn.SetParent(View);
                mbtn.MakeConstraints(m =>
                {
                    m.Top.EqualTo(this.TopLayoutGuideBottom());
                    m.Right.EqualTo(View);
                    m.Width.Height.EqualTo(NSObject.FromObject(50));
                });
                mbtn.TouchUpInside += delegate { ShowDevServers(); };
            });

            FFImageLoading.Forms.Platform.CachedImageRenderer.Init();
            var tt = new FFImageLoading.Transformations.BlurredTransformation();
            var ike = Plugin.InputKit.CrossInputKit.IsSupported;
            var gi = Grpc.Core.ChannelCredentials.Insecure;
        }

        void TestForm()
        {

            Forms.Init();
            var fvc = new TipCalc.TipCalcPage().CreateViewController();
            fvc.View.SetParent(View);
            fvc.View.BackgroundColor = UIColor.Blue;
            fvc.View.MakeConstraints(m =>
            {
                m.Left.Right.EqualTo(View);
                m.Height.EqualTo(NSObject.FromObject(400));
                m.Bottom.EqualTo(PrgUpdate.Top()).Offset(-10);
            });
            AddChildViewController(fvc);
            fvc.DidMoveToParentViewController(this);
        }

        public override void ViewDidAppear(bool animated)
        {

            var autoServer = startOption.GetStringValue("autoserver");
            if( autoServer == "open" ) {
                ShowDevServers();
            }
            else if( autoServer != null ) {
                var uri = App.AssetServerURI;
                var svInfo = autoServer.Split(":");
                var host = svInfo[0];
                var port = svInfo.Length == 2 ? int.Parse(svInfo[1]) : uri.Item2 - 10000;
                StartUpdate("test", host, port);
            }
            else {

                new ServerLoader().StartLoad(async (rt, msg) =>
                {
                    logger.Log("load-->", rt);
                    if( rt == ServerLoader.LoadResult.STEP_NOTIFY ) {
                        LabTitle.Text = "配置加载中:" + msg;
                    }
                    else if( rt == ServerLoader.LoadResult.NOT_AVAILABLE ) {
                        MyPopupManager.ShowMsgBox(msg);
                    }
                    else if( rt == ServerLoader.LoadResult.NEED_UPDATE ) {
                        MyPopupManager.ShowMsgBox("当前版本太低，请更新", onClick: () =>
                        {
                            string url = msg;
                            if( url.StartsWith("itms-services://") ) {
                                var urlPlist = "https://mj.19v5.com:19382/test/step.plist";
                                urlPlist = url;
                                var urlInstall = $"itms-services://?action=download-manifest&url={urlPlist}";
                                logger.Log("click inside", urlInstall);
                                UIApplication.SharedApplication.OpenUrl(NSUrl.FromString(urlInstall));
                            }
                            else {
                                Xamarin.Essentials.Browser.OpenAsync(url, BrowserLaunchMode.External);
                            }

                        });
                    }
                    else {
                        isLoading = false;
                        LabTitle.Text = "点击屏幕进入程序";

                        mb.Util.DoWhenTestFlag(actNo: () =>
                        {
                            StartUpdate("default", App.AssetServerURI.Item1, App.AssetServerURI.Item2);
                        });
                    }
                });
            }
        }

        void ShowDevServers()
        {
            DevServerViewController vcDevServer = null;
            vcDevServer = new DevServerViewController();
            vcDevServer.OnSelect = (name, url, port) =>
            {
                logger.Log("select server", name, url);
                vcDevServer.DismissModalViewController(true);
                StartUpdate("test", url, port);
            };

            PresentViewController(vcDevServer, false, null);
        }

        void StartUpdate(string group, string url, int port)
        {
            App.HotStorageRoot = Xamarin.Essentials.FileSystem.CacheDirectory + "/hotupdate/" + updateGroup;
            App.CurrentServerUrl = $"{url}:{port}";
            var updater = mb.ServiceLocator.Instance.Get<API.IAssetUpdater>();
            updater.SetFullUpdate(startOption.GetBoolValue("fullupdate"));
            updater.SetNotifyHandler(this);
            updater.StartUpdate(url, port);
        }

        public void notifyBegin()
        {
            PrgUpdate.Hidden = false;
            // LabTitle.Layer.RemoveAllAnimations();
            // LabTitle.Alpha = 1.0f;
        }

        public void notifyDescription(string text)
        {
            LabTitle.Text = text;
        }

        public void notifyProgress(float percent)
        {
            PrgUpdate.Progress = percent;
        }

        public void notifyEnd(bool succeed, string errMsg = "")
        {
            if( succeed ) {
                var dllData = File.ReadAllBytes(getStorageRoot() + $"/libmp.dll.ios");
                var pdbData = File.ReadAllBytes(getStorageRoot() + $"/libmp.pdb.ios");
                IHotLoader loader = ServiceLocator.Instance.Get<IHotLoader>();
                loader.Load(dllData, pdbData);
            }
            else {
                LabTitle.Text = errMsg;
            }
        }

        public bool isFileNeed(string path)
        {
            return true;
        }

        public bool shouldFileRemove(string path)
        {
            return true;
        }

        public string getStorageRoot() => App.HotStorageRoot;
    }
}